package com.vzoom.logdesensitization.strategyimpl;

import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import com.vzoom.logdesensitization.DesensitizationStrategy;
import com.vzoom.logdesensitization.util.XmlMappers;
import org.springframework.beans.factory.InitializingBean;

import java.io.IOException;

public class XmlStrDesensitizationStrategy implements DesensitizationStrategy, InitializingBean {

    private static XmlMapper xmlMapper;

    @Override
    public String desensitization(Object origin) {
        if (origin instanceof String) {
            try {
                String xmlStr = (String) origin;
                //find root name
                int index = xmlStr.indexOf("?>");
                int start;
                int end;
                if (index >= 0) {
                    int fromIndex = index + 2;
                    start = xmlStr.indexOf('<', fromIndex);
                    end = xmlStr.indexOf('>', fromIndex);
                } else {
                    start = xmlStr.indexOf('<');
                    end = xmlStr.indexOf('>');
                }
                String rootName = xmlStr.substring(start + 1, end);
                Object jsonNode = xmlMapper.readValue(xmlStr, Object.class);
                return xmlMapper.writer().withRootName(rootName).writeValueAsString(jsonNode);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        } else {
            return String.valueOf(origin);
        }
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        xmlMapper = XmlMappers.getXmlMapper();
    }
}
